import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../theme.dart';

/// 摄像头画面设置
class FramesPage extends StatefulWidget {
  final String deviceId;

  const FramesPage({super.key, required this.deviceId});

  @override
  State<StatefulWidget> createState() {
    return _FramesPageState();
  }
}

class _FramesPageState extends State<FramesPage> {
  late String _deviceId;

  // 指令示例
  late Pipe _pipe;

  // 设备开关
  bool _isSwitched = false;

  String _selectedValue = "0";

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;

    LogUtils.w("设备ID${_deviceId}");

    // 创建实例
    _pipe = Pipe.create(_deviceId);
    // 连接设备
    _pipe.establish();

    // _pipe.listen((state) {
    //   LogUtils.w(state);
    //   if (state == PipeState.established) {
    //     // 连接成功建立，可以启动视频播放、发送指令或者其他操作了
    //     _onQuality();
    //   }
    // });

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("页面渲染完毕");
      _onQuality();
    });

  }

  @override
  void dispose() {
    super.dispose();
    // 销毁实例
    _pipe.abolish();
    _pipe.destroy();
  }

  void _onQuality() async {
    if (!_pipe.isEstablished) return;
    LogUtils.w("========执行=======");
    final resp = await InstructStandard.picture(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w(resp.data!.mode);
      setState(() {
        _selectedValue = "${resp.data?.mode ?? "999"}";
      });
    } else {
      showToast("获取画面设置失败");
    }
  }

  Future<bool> _onWillPop() async {
    // HomePageState.globalKeytwo.currentState?.reloadData();
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xFFF2F3F5),
        appBar: _buildTitleBar(context),
        body: Padding(
          padding: EdgeInsets.all(16.0), // 这里设置内边距，可以根据需要调整数值
          child: Column(
            children: [
              // 添加本地图片
              Container(
                width: double.infinity, // 宽度撑满
                height: 200, // 高度200
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12), // 设置圆角半径
                  child: Transform.rotate(
                    angle: _selectedValue == "3" ? 3.14159 : 0, // 180°时翻转图片
                    child: Image.asset(
                      'assets/app_img/videonodata.png', // 替换为你的本地图片路径
                      fit: BoxFit.cover, // 图片填充方式
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20),
              _buildreportRow(),
            ],
          ),
        ),
      ),
      onWillPop: _onWillPop,
    );
  }

  Widget _buildreportRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 5, // 上边距
        bottom: 5, // 下边距
        left: 5, // 左边距
        right: 5, // 右边距
      ),
      child: Column(
        children: [
          // 第一行：0°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '0°',
                    style: TextStyle(fontSize: 16),
                  ),
                  Radio(
                    value: "0",
                    groupValue: _selectedValue,
                    onChanged: (value) async {
                      if (!_pipe.isEstablished) return;
                      LogUtils.w("========执行正常=======");
                      final resp = await InstructStandard.setPicture(_pipe, 0);
                      if (!mounted) return;
                      if (resp.success) {
                        setState(() {
                          _selectedValue = "0";
                        });
                        showToast("设置画面成功");
                      } else {
                        showToast("设置画面失败");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
          // 第二行：180°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '180°',
                    style: TextStyle(fontSize: 16),
                  ),
                  Radio(
                    value: "3",
                    groupValue: _selectedValue,
                    onChanged: (value) async {
                      if (!_pipe.isEstablished) return;
                      LogUtils.w("========执行正常=======");
                      final resp = await InstructStandard.setPicture(_pipe, 3);
                      if (!mounted) return;
                      if (resp.success) {
                        setState(() {
                          _selectedValue = "3";
                        });
                        showToast("设置画面成功");
                      } else {
                        showToast("设置画面失败");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 导航
  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          _onWillPop();
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      title: Text(
        "画面设置",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
